<?php
namespace app\admin\controller;
use think\Db;
use lib\Curl;
class Streets extends Base{
    public function street_list(){
        $keyword=input('get.keyword');
        if (!empty(input('get.fromtime'))) {
            $fromtime=strtotime(input('get.fromtime'));
        }else{
            $fromtime=0;
        }
        if (!empty(input('get.totime'))) {
            $totime=strtotime(input('get.totime'))+86400;
        }else{
            $totime=time();
        }
        $list=Db::name('street')->where('time','>',"{$fromtime}")->where('time','<',"{$totime}")->where('uuid|city|street','like',"%{$keyword}%")->where('state','<',3)->order('id desc')->paginate(10);
        $count=Db::name('street')->where('time','>',"{$fromtime}")->where('time','<',"{$totime}")->where('uuid|city|street','like',"%{$keyword}%")->where('state','<',3)->count();
        $this->assign('keyword',input('get.keyword'));
        $this->assign('fromtime',input('get.fromtime'));
        $this->assign('totime',input('get.totime'));
        $this->assign('list',$list);
        $this->assign('count',$count);
        return $this->fetch();
    }
    public function street_add(){
        if(request()->isGet()){
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            $data['uuid']=$param['uuid'];
            $data['city']=$param['city'];
            $data['street']=$param['street'];
            $data['qrcode']=$param['qrcode'];
            $data['img']=$param['img'];
            $data['time']=time();
            $data['uptime']=time();
            $res= Db::name('street')->insert($data);
            if($res){
                return json(['code' => 200, 'msg' => '成功！']);
            }else{
                return json(['code' => 500, 'msg' => '失败！']);
            }
        }
    }
    public function street_edit(){
        if(request()->isGet()){
            $param = input('get.');
            $data=Db::name('street')->where('id',$param['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            $data['uuid']=$param['uuid'];
            $data['city']=$param['city'];
            $data['street']=$param['street'];
            $data['qrcode']=$param['qrcode'];
            $data['img']=$param['img'];
            $data['uptime']=time();
            $res=Db::name('street')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '成功！']);
            }else{
                return json(['code' => 500, 'msg' => '失败！']);
            }
        }
    }
    public function street_del(){
        $param = input('post.');
        $res= Db::name('street')->where(array('id'=>$param['id']))->update(['state'=>3]);
        return json(['code' => 200,'msg' => '删除成功']);

    }
    // 生成二维码
    public function qrcodes()
    {   
        $all=Db::name('street')->field('id,qrcode')->where('state',1)->order('id asc')->select();
        foreach ($all as $key => $value) {
            // type(1:街道巷;2:楼幢;3:单元;4:室)
            $url=config('http_https').$_SERVER['HTTP_HOST'].'/index/index/index.html?type=1&id='.$all[$key]['id'];
            $qrcode_path=$this->scerweima($url,1,$all[$key]['id']);
            Db::name('street')->where('id',$all[$key]['id'])->update(['qrcode'=>$qrcode_path]);
            $date_path=substr($all[$key]['qrcode'],16,8);
            if ($all[$key]['qrcode']&&file_exists("../public".$all[$key]['qrcode'])&&date('Ymd',time())>$date_path) {
                unlink("../public".$all[$key]['qrcode']);
            }
        }
        return json(['code' => 200,'msg' => '成功']);
    }
    // 生成牌
    public function plates()
    {
        $all=Db::name('street')->field('id,city,street,qrcode,img')->where('state',1)->order('id asc')->select();
        foreach ($all as $key => $value) {
            // type(1:街道巷;2:楼幢;3:单元;4:室)
            if ($all[$key]['street']) {
                $char=$all[$key]['street'];
                $pinyin=$this->get_all_py($all[$key]['street']);
            }else{
                $char=$all[$key]['city'];
                $pinyin=$this->get_all_py($all[$key]['city']);
            }
            $pinyin=implode(' ',$pinyin);
            $plate_path=$this->plateImg($all[$key]['id'],$all[$key]['qrcode'],1,$char,$pinyin,0);
            Db::name('street')->where('id',$all[$key]['id'])->update(['img'=>$plate_path]);
            $date_path=substr($all[$key]['img'],16,8);
            if ($all[$key]['img']&&file_exists("../public".$all[$key]['img'])&&date('Ymd',time())>$date_path) {
                unlink("../public".$all[$key]['img']);
            }
        }
        return json(['code' => 200,'msg' => '成功']);
    }
    public function phpexcelin(){
        if(request()->isGet()){
         return $this->fetch();
        }
        if(request() -> isPost())
        {
            $file = request()->file('excel');
         //将文件保存到public/uploads目录下面
            $info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( './uploads');
            if($info){
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = "..".DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$fileName;
                //获取文件后缀
                $suffix = $info->getExtension();
                //判断哪种类型
                if($suffix=="xlsx"){
                    $reader = \PHPExcel_IOFactory::createReader('Excel2007');
                }else{
                    $reader = \PHPExcel_IOFactory::createReader('Excel5');
                }
            }else{
                $this->error('文件过大或格式不正确导致上传失败-_-!');
            }
            //载入excel文件
            $excel = $reader->load("$filePath",$encode = 'utf-8');
            //读取第一张表
            $sheet = $excel->getSheet(0);
            //获取总行数
            $row_num = $sheet->getHighestRow();
            //获取总列数
            $col_num = $sheet->getHighestColumn();
            $data = []; //数组形式获取表格数据
            for ($i = 1; $i <= $row_num; $i ++) {
                $data[$i]['uuid']  = $sheet->getCell("A".$i)->getValue();
                $data[$i]['city']  = $sheet->getCell("B".$i)->getValue();
                $data[$i]['street']  = $sheet->getCell("C".$i)->getValue();
                //将数据保存到数据库
            }
            $res=Db::name('street')->insertAll($data);
            if ($res) {
                return json(['code' => 200,'msg' => '成功']);
            }else{
                return json(['code' => 500,'msg' => '失败']);
            }
        }
    }
    public function phpexcelout() {
        $result=Db::name('street')->where('state',1)->select();
        foreach ($result as $key => $value) {
            $result[$key]['time']=date('Y-m-d H:i:s',$result[$key]['time']);
            $result[$key]['uptime']=date('Y-m-d H:i:s',$result[$key]['uptime']);
        }
        $xlsCell  = array(
            array('id','ID'),
            array('uuid','UUID'),
            array('city','上级行政区域乡镇（街道）名称'),
            array('street','街路巷名称')
            // array('id','id'),
            // array('uuid','uuid'),
            // array('city','city'),
            // array('street','street'),
            // array('qrcode','qrcode'),
            // array('img','img'),
            // array('state','state'),
            // array('time','time'),
            // array('uptime','uptime')
        );
        $this->exportexcel('街道巷列表',$xlsCell,$result);
    }
    private function exportexcel($expTitle, $expCellName, $expTableData) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $xlsTitle;//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        // Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 1), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}